package com.secure.orm.thirdPay.alipay;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.secure.common.util.PayUtil;
import com.secure.orm.enums.PayType;
import com.secure.orm.enums.PaymentOrderType;
import com.secure.orm.enums.ThirdPayNotifyType;
import com.secure.orm.model.PayOrder;
import com.secure.orm.model.response.ViewData;
import com.secure.orm.thirdPay.AbstractThirdPay;

public class Alipay extends AbstractThirdPay {
	
	public static final String TRADE_FINISHED = "TRADE_FINISHED" ;
	public static final String TRADE_SUCCESS = "TRADE_SUCCESS" ;
	public static final String TRADE_WAIT_BUYER_PAY = "WAIT_BUYER_PAY";
	public static final String TRADE_TRADE_CLOSED = "TRADE_CLOSED";
	public static final String TRADE_TRADE_PENDING = "TRADE_PENDING";
	
	//支付宝 notify_url 需要 返回的两种值
	public static final String NOTIFY_SUCCESS_RESULT = "success";
	public static final String NOTIFY_FAIL_RESULT = "fail";
	
	//支付宝 支付涉及的参数名
	public static final String ALIPAY_OUT_TRADE_NO = "out_trade_no";
	public static final String ALIPAY_SUBJECT = "subject";
	public static final String ALIPAY_TRADE_STATUS = "trade_status";
    public static final String ALIPAY_TRADE_NO = "trade_no";
    public static final String ALIPAY_BUYER_ID = "buyer_id";
    public static final String ALIPAY_TOTAL_FEE = "total_fee";
	
	//支付宝 部分参数默认值
	public static final String ALIPAY_PAYMETHOD = "bankPay";
	
	public Alipay(){
		super();
	}

	@Override
	public String pay(PayOrder payOrder) {
		Map<String, String> sParaTemp = null;
		if(null == payOrder || null == payOrder.getOrderId())
			return null ;
		sParaTemp = new HashMap<String, String>() ;
        String domain = properties.getProperty("base.domain").trim();
		sParaTemp.put("service", AlipayConfig.service);
	    sParaTemp.put("partner", properties.getProperty("alipay.partner"));
	    sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", AlipayConfig.payment_type);
		sParaTemp.put("notify_url", domain+properties.getProperty("alipay.notify_url"));
		sParaTemp.put("return_url", domain+properties.getProperty("alipay.return_url"));

		sParaTemp.put("seller_email", AlipayConfig.seller_email);
		sParaTemp.put("out_trade_no", payOrder.getOrderId());
		sParaTemp.put("subject", payOrder.getSubject());
		
		// 金额
		int totalFee = PayUtil.mulToInt(String.valueOf(payOrder.getOrderAmount()), String.valueOf(100));
		sParaTemp.put("total_fee", String.valueOf(totalFee));
		
		String defaultBank =  payOrder.getPayWay();
		//网银接口
		if(StringUtils.isNotBlank(defaultBank) && !"alipay".equals(defaultBank)){
			sParaTemp.put("paymethod", ALIPAY_PAYMETHOD);
			sParaTemp.put("defaultbank", payOrder.getPayWay());
		}		
		sParaTemp.put("body",AlipayConfig.body);
		
		Map<String,String> strParametersMap = mergeSign(sParaTemp);		
		return PayUtil.buildForm(properties.getProperty("alipay.gate_url"), strParametersMap, "POST");
	}
	
	public Map<String, String> mergeSign(Map<String, String> Params) {
		 //除去数组中的空值和签名参数
        Map<String, String> sPara = AlipayCore.paraFilter(Params);
        String prestr = AlipayCore.createLinkString(sPara); //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        String mysign = "";
        if(AlipayConfig.sign_type.equals("MD5") ) {
        	mysign = MD5.sign(prestr, properties.getProperty("alipay.key"), AlipayConfig.input_charset);
        }
        sPara.put("sign", mysign);
        sPara.put("sign_type", AlipayConfig.sign_type);
		return sPara;
	}

	/**
	 * 处理支付宝 通知返回的参数
	 * 支付宝 返回订单状态
	 *  WAIT_BUYER_PAY
		TRADE_CLOSED
		TRADE_SUCCESS
		TRADE_FINISHED
		TRADE_PENDING
	 */
	@Override
	public ViewData handleResponse(Map<String,String> requestParamsMap,ThirdPayNotifyType thirdPayNotifyType){
		ViewData view = verifyThirdPayResponse(requestParamsMap) ;
		
		String tradeStatus = requestParamsMap.get(Alipay.ALIPAY_TRADE_STATUS) ;
		String orderId = requestParamsMap.get(Alipay.ALIPAY_OUT_TRADE_NO);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if(view.getCode()==-1){
			resultMap.put(orderId, PayType.Alipay.name()+"notify verify fail");
		}else{
			if(Alipay.TRADE_FINISHED.equals(tradeStatus) || Alipay.TRADE_SUCCESS.equals(tradeStatus)){
				resultMap.put(orderId, PayType.Alipay.name()+PaymentOrderType.SCCUESS.name());
			}else{
				if(thirdPayNotifyType.getValue() == ThirdPayNotifyType.RETURN.getValue())
					view.setCode(-1);
				resultMap.put(orderId, PayType.Alipay.name()+tradeStatus);
			}
		}
		view.setResult(resultMap);
		return view;
	}
	
	
	/**
	 * 判断响应签名
	 * @param requestParamsMap
	 * @return
	 */
	private ViewData verifyThirdPayResponse(Map<String,String> requestParamsMap){
		boolean verify_result = AlipayNotify.verify(requestParamsMap);
		if(!verify_result)
			return new ViewData(-1, "verify fail", null);
		return new ViewData(0, "verify success", null);
	}

}
